<template>
  <view class="container">
    <!-- 当前病情 -->
    <view class="section current-condition-section">
      <view class="section-header" @click="currentConditionCollapsed = !currentConditionCollapsed">
        <text class="section-title">{{ t('medical.current_condition') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ currentConditionCollapsed ? '▼' : '▲' }}</text>
      </view>
      
      <view v-show="!currentConditionCollapsed" class="section-content">
        <!-- 主诉症状 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.main_complaint') }}</view>
          <textarea 
            v-model="formData.main_complaint" 
            class="write-textarea" 
            :placeholder="t('medical.main_complaint_placeholder')"
          />
        </view>

        <!-- 疼痛描述 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.pain_description') }}</view>
          <view class="pain-description-container">
            <view 
              v-for="item in (optionalInfo && optionalInfo.pain_description ? optionalInfo.pain_description : [])" 
              :key="item.id"
              class="pain-description-item"
              :class="{ 'selected': isPainDescriptionSelected(item.id) }"
              @click="onPainDescriptionChange(item.id)"
            >
              <text class="pain-item-label">{{ getCurrentLanguage() === 'zh' ? item.label : item.value }}</text>
            </view>
          </view>
          
          <!-- 显示已选择的疼痛描述 -->
          <view v-if="formData.pain_description" class="selected-pain-items">
            <text class="selected-title">{{ t('medical.selected_pain_description') }}</text>
            <text class="selected-tag">
              {{ getPainDescriptionLabel(formData.pain_description) }}
              <text class="remove-tag" @click="removePainDescriptionItem()" :aria-label="t('common.delete')">×</text>
            </text>
          </view>
        </view>

        <!-- 疼痛强度 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.pain_intensity') }}</view>
          <view class="pain-intensity-container">
            <view class="intensity-options">
              <view 
                v-for="intensity in 11" 
                :key="intensity - 1"
                class="intensity-option"
                :class="{ 'selected': formData.pain_intensity === (intensity - 1) }"
                @click="onPainIntensityChange(intensity - 1)"
              >
                <text class="intensity-number">{{ intensity - 1 }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 既往治疗史 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.past_treatment') }}</view>
          <textarea 
            v-model="formData.past_treatment" 
            class="write-textarea" 
            :placeholder="t('medical.past_treatment_placeholder')"
          />
        </view>

        <!-- 伴随症状/体征 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.accompany_symptom') }}</view>
          <textarea 
            v-model="formData.accompany_symptom" 
            class="write-textarea" 
            :placeholder="t('medical.accompany_symptom_placeholder')"
          />
        </view>
      </view>
    </view>

    <!-- 患者同意声明 -->
    <view class="section consent-declaration-section">
      <view class="section-header" @click="consentDeclarationCollapsed = !consentDeclarationCollapsed">
        <text class="section-title">{{ t('medical.consent_declaration') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ consentDeclarationCollapsed ? '▼' : '▲' }}</text>
      </view>
      
      <view v-show="!consentDeclarationCollapsed" class="section-content">
        <!-- 同意声明内容 -->
        <view class="consent-content">
          <text class="consent-text">{{ t('medical.consent_declaration_text') }}</text>
        </view>
        
        <!-- 患者信息 -->
        <view class="signature-section">
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_name') }}</view>
            <view class="signature-value">{{ getPatientFullName() }}</view>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_signature') }}</view>
            <view class="signature-display">
              <image 
                v-if="memberInfo && memberInfo.signature_url" 
                :src="memberInfo.signature_url" 
                class="signature-image" 
                mode="aspectFit"
              />
              <text v-else class="no-signature">{{ t('medical.no_signature') }}</text>
            </view>
            <button class="re-sign-btn" @click="gotoPatientSign">{{ t('medical.re_sign') }}</button>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_date') }}</view>
            <view class="signature-value">{{ getCurrentDate() }}</view>
          </view>
        </view>
        
        
      </view>
    </view>

    <!-- 固定底部提交按钮 -->
    <view class="fixed-bottom-btn">
      <button class="fill-btn" @click="goToNextStep">{{ t('medical.next_step') }}</button>
    </view>
  </view>
</template>

<script>
import { useI18n } from 'vue-i18n'
import { getOptionalInfo } from '@/api/medical.js'
import { useUserStore } from '@/store/user.js'
import { uploadSignature, resetSignature } from '@/api/user.js'

export default {
  data() {
    return {
      currentConditionCollapsed: false, // 当前病情折叠状态
      consentDeclarationCollapsed: false, // 患者同意声明折叠状态
      memberInfo: {}, // 会员信息
      
      formData: {
        patient_id: '',         // 患者ID
        // 当前病情字段
        main_complaint: '',    // 主诉症状
        past_treatment: '', // 既往治疗史
        accompany_symptom: '', // 伴随症状/体征
        pain_description: '',   // 疼痛描述 - 单选
        pain_intensity: 0      // 疼痛强度 - 单选，0-10
      },
      // 可选信息数据
      optionalInfo: {
        select_item: [], // 需要用户选择的项目
        optional_item: [], // 可选项目
        write_item: [], // 需要书写的项目
        pain_description: [] // 疼痛描述
      }
    }
  },
  
  setup() {
    const { t } = useI18n()
    const userStore = useUserStore()
    
    // 动态设置页面标题以支持国际化
    if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
      uni.setNavigationBarTitle({
        title: t('medical.current_condition')
      })
    }
    return { t, userStore }
  },
  
  onReady() {
    // 进入页面时设置国际化标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.current_condition')
      })
    }
  },

  computed: {
    userInfo() {
      return this.userStore.userInfo
    }
  },

  onShow() {
    // 设置页面标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.current_condition')
      })
    }
    
    // 优先从本地存储获取病史记录数据（包含患者信息）
    const medicalHistoryData = uni.getStorageSync('medical_history_data');
    if (medicalHistoryData && medicalHistoryData.patient_id) {
      this.memberInfo = medicalHistoryData.patient_info;
      this.formData.patient_id = medicalHistoryData.patient_id;
    } else {
      // 如果没有病史记录数据，尝试从患者信息存储中获取
      const patientInfo = uni.getStorageSync('medical_patient_info');
      if (patientInfo && patientInfo.patient_info) {
        this.memberInfo = patientInfo.patient_info;
        this.formData.patient_id = patientInfo.patient_id;
      }
    }
    
    
    
    // 获取可选信息
    this.loadOptionalInfo();
    
  },

  methods: {
    // 加载可选信息
    async loadOptionalInfo() {
      try {
        const response = await getOptionalInfo();
        if (response && response.result) {
          this.optionalInfo = response.result;
        }
      } catch (error) {
        console.error('获取可选信息失败:', error);
      }
    },
    
    // 获取当前语言
    getCurrentLanguage() {
      return this.$i18n.locale || 'zh';
    },

    // 疼痛描述相关方法
    onPainDescriptionChange(itemId) {
      // 单选逻辑：如果点击的是已选中的，则取消选择；否则选择新的
      if (this.formData.pain_description === itemId) {
        this.formData.pain_description = '';
      } else {
        this.formData.pain_description = itemId;
      }
    },

    isPainDescriptionSelected(itemId) {
      return this.formData.pain_description === itemId;
    },

    getPainDescriptionLabel(itemId) {
      if (!this.optionalInfo || !this.optionalInfo.pain_description || !Array.isArray(this.optionalInfo.pain_description)) {
        return '';
      }
      const item = this.optionalInfo.pain_description.find(item => item.id === itemId);
      return item ? (this.getCurrentLanguage() === 'zh' ? item.label : item.value) : '';
    },

    removePainDescriptionItem() {
      this.formData.pain_description = '';
    },

    // 疼痛强度相关方法
    onPainIntensityChange(intensity) {
      this.formData.pain_intensity = intensity;
    },

    // 获取患者全名
    getPatientFullName() {
      if (this.memberInfo && this.memberInfo.first_name && this.memberInfo.last_name) {
        return `${this.memberInfo.last_name}${this.memberInfo.first_name}`;
      } else if (this.memberInfo && this.memberInfo.username) {
        return this.memberInfo.username;
      } else if (this.memberInfo && this.memberInfo.name) {
        return this.memberInfo.name;
      } else {
        return this.t('medical.not_filled');
      }
    },

    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },



    // 患者重新签名
    gotoPatientSign() {
      // 跳转签名页，签名完成后回传图片
      uni.navigateTo({
        url: '/pages/order/sign',
        events: {
          signImage: (img) => {
            this.updatePatientSignature(img);
          }
        }
      });
    },



    // 更新患者签名
    async updatePatientSignature(img) {
      try {
        // console.log("当前患者信息:", this.memberInfo);
        
        // 检查是否有患者信息
        if (!this.memberInfo) {
          uni.showToast({ 
            title: this.t('medical.patient_info_required'), 
            icon: 'error' 
          });
          return;
        }
        
        if (!this.formData.patient_id) {
          // 新患者，上传签名
          const res = await uploadSignature({ 
            signature: img,
          });
          if (res.code == 200) {
            this.memberInfo.signature_url = res.result.url;
            this.memberInfo.signature = res.result.save_path;
            
            // 更新本地存储的患者信息
            this.updateLocalPatientInfo();
            
            uni.showToast({ 
              title: this.t('medical.signature_updated'), 
              icon: 'success' 
            });
          }
        } else {
          // 已有患者，重置签名
          const res = await resetSignature({ 
            signature: img, 
            user_id: this.formData.patient_id
          });
          if (res.code == 200) {
            this.memberInfo.signature_url = res.result.url;
            this.memberInfo.signature = res.result.save_path;
            
            // 更新本地存储的患者信息
            this.updateLocalPatientInfo();
            
            uni.showToast({ 
              title: this.t('medical.signature_updated'), 
              icon: 'success' 
            });
          }
        }
      } catch (error) {
        console.error('更新患者签名失败:', error);
        uni.showToast({ 
          title: this.t('common.update_failed'), 
          icon: 'error' 
        });
      }
    },

    // 更新本地存储的患者信息
    updateLocalPatientInfo() {
      try {
        // 更新病史记录数据中的患者信息
        const medicalHistoryData = uni.getStorageSync('medical_history_data');
        if (medicalHistoryData) {
          medicalHistoryData.patient_info = this.memberInfo;
          uni.setStorageSync('medical_history_data', medicalHistoryData);
        }
        
        // 更新患者信息存储
        const patientInfo = uni.getStorageSync('medical_patient_info');
        if (patientInfo) {
          patientInfo.patient_info = this.memberInfo;
          uni.setStorageSync('medical_patient_info', patientInfo);
        }
        
        // console.log('本地存储的患者信息已更新');
      } catch (error) {
        console.error('更新本地存储失败:', error);
      }
    },



    // 跳转到下一步 - 诊断和中药选择页面
    goToNextStep() {
        // console.log('当前患者信息:', this.memberInfo);
      // 验证患者信息
      if (!this.memberInfo) {
        uni.showToast({ 
          title: this.t('medical.patient_info_required'), 
          icon: 'error' 
        });
        return;
      }

      // 准备完整的医疗记录数据
      const medicalRecordData = {
        ...this.formData,
        doctor_id: this.userInfo && this.userInfo.id ? this.userInfo.id : null,
        doctor_signature: this.userInfo && this.userInfo.signature_path ? this.userInfo.signature_path : '',
        signature_date: this.getCurrentDate(),
        patient_info: this.memberInfo // 确保包含完整的患者信息
      };

      // 从本地存储获取病史记录数据
      const medicalHistoryData = uni.getStorageSync('medical_history_data');
      if (medicalHistoryData) {
        Object.assign(medicalRecordData, medicalHistoryData);
      }

      // console.log('提交医疗记录数据:', medicalRecordData);

      // 将完整的医疗记录数据存储到本地，供诊断和中药选择页面使用
      uni.setStorageSync('medical_complete_record', medicalRecordData);
      
      // 跳转到诊断和中药选择页面
      uni.navigateTo({
        url: '/pages/medicine/prescription'
      });
    }
  }
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
  overflow-x: hidden;
  box-sizing: border-box;
}

.section {
  background: #fafafa;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #eee;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  max-width: calc(100% - 48rpx);
  box-sizing: border-box;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  cursor: pointer;
  user-select: none;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #1976d2;
}

.flex-spacer {
  flex: 1;
}

.collapse-arrow {
  color: #888;
  font-size: 24rpx;
}

.section-content {
  margin-top: 20rpx;
}

/* 当前病情样式 */
.current-condition-section {
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.write-form-item {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
  margin-top: 16rpx;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.write-label {
  font-size: 32rpx;
  color: #1976d2;
  font-weight: 600;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.write-textarea {
  width: 100%;
  padding: 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 30rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-height: 80rpx;
  max-height: 120rpx;
  resize: vertical;
  box-sizing: border-box;
  line-height: 1.4;
  display: block;
  min-width: 0;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
}

.write-textarea:focus {
  border-color: #1976d2;
  outline: none;
}

/* 疼痛描述样式 */
.pain-description-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150rpx, 1fr));
  gap: 16rpx;
  margin-top: 16rpx;
}

.pain-description-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 12rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 8rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 80rpx;
  box-sizing: border-box;
}

.pain-description-item:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.15);
}

.pain-description-item.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.pain-item-label {
  font-size: 24rpx;
  color: #333;
  font-weight: 600;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}

.pain-description-item.selected .pain-item-label {
  color: #1976d2;
  font-weight: 700;
}

.selected-pain-items {
  width: 100%;
  margin-top: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.selected-title {
  font-size: 24rpx;
  color: #1976d2;
  font-weight: 600;
  margin-right: 16rpx;
}

.selected-tag {
  display: inline-block;
  background: #1976d2;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  margin: 8rpx 8rpx 8rpx 0;
  position: relative;
}

.remove-tag {
  margin-left: 8rpx;
  font-weight: bold;
  cursor: pointer;
  padding: 0 4rpx;
}

.remove-tag:hover {
  color: #ffebee;
}

/* 疼痛强度样式 */
.pain-intensity-container {
  width: 100%;
  margin-top: 16rpx;
}

.intensity-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  margin-top: 16rpx;
  justify-content: flex-start;
}

.intensity-option {
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(9.09% - 8rpx);
  min-width: 60rpx;
  padding: 16rpx 8rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 8rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 60rpx;
  box-sizing: border-box;
  flex-shrink: 0;
  flex-grow: 0;
}

.intensity-option:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.15);
}

.intensity-option.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.intensity-option .intensity-number {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.intensity-option.selected .intensity-number {
  color: #1976d2;
  font-weight: 700;
}

/* 患者同意声明样式 */
.consent-declaration-section {
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.consent-content {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.consent-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
  text-align: justify;
  word-break: break-word;
}

.signature-section {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.signature-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.signature-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.signature-label {
  font-size: 28rpx;
  color: #1976d2;
  font-weight: 600;
  min-width: 160rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.signature-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.signature-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.signature-image {
  width: 120rpx;
  height: 60rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  background: #fff;
}

.no-signature {
  font-size: 24rpx;
  color: #999;
  font-style: italic;
}

.re-sign-btn {
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  margin-left: 16rpx;
  height: 48rpx;
  line-height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border: none;
  white-space: nowrap;
  flex-shrink: 0;
}

.fixed-bottom-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 8rpx #eee;
}

.fill-btn {
  width: 100%;
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: block;
}

/* 响应式布局调整 */
@media screen and (max-width: 750rpx) {
  .pain-description-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 12rpx;
  }
  
  .pain-description-item {
    min-height: 70rpx;
    padding: 12rpx 8rpx;
  }
  
  .pain-item-label {
    font-size: 22rpx;
  }

  .intensity-options {
    gap: 6rpx;
    justify-content: flex-start;
  }
  
  .intensity-option {
    width: calc(9.09% - 6rpx);
    min-width: 50rpx;
    min-height: 50rpx;
    padding: 12rpx 4rpx;
    flex-grow: 0;
  }
  
  .intensity-option .intensity-number {
    font-size: 24rpx;
  }

  .consent-text {
    font-size: 24rpx;
  }

  .signature-label {
    font-size: 26rpx;
    min-width: 140rpx;
  }

  .signature-value {
    font-size: 26rpx;
  }

  .signature-image {
    width: 100rpx;
    height: 50rpx;
  }

  .re-sign-btn {
    font-size: 22rpx;
    padding: 6rpx 12rpx;
    height: 40rpx;
    line-height: 28rpx;
  }
}

@media screen and (min-width: 751rpx) {
  .pain-description-container {
    grid-template-columns: repeat(4, 1fr);
    gap: 20rpx;
  }
  
  .pain-description-item {
    min-height: 90rpx;
    padding: 20rpx 16rpx;
  }
  
  .pain-item-label {
    font-size: 26rpx;
  }

  .intensity-options {
    gap: 12rpx;
    justify-content: flex-start;
  }
  
  .intensity-option {
    width: calc(9.09% - 12rpx);
    min-width: 70rpx;
    min-height: 70rpx;
    padding: 20rpx 8rpx;
    flex-grow: 0;
  }
  
  .intensity-option .intensity-number {
    font-size: 32rpx;
  }

  .consent-text {
    font-size: 28rpx;
  }

  .signature-label {
    font-size: 30rpx;
    min-width: 180rpx;
  }

  .signature-value {
    font-size: 30rpx;
  }

  .signature-image {
    width: 140rpx;
    height: 70rpx;
  }

  .re-sign-btn {
    font-size: 26rpx;
    padding: 10rpx 20rpx;
    height: 56rpx;
    line-height: 36rpx;
  }
}
</style>